#!/usr/bin/python3
# -*- coding: utf-8 -*-

from coreweb import get, post
from datetime import datetime

import db

@get('/clipboard/delete/{id}')
async def delete_clipboard(*, id, request):
    try:
        session = db.create_session()
        item = session.query(db.Clipboard).filter(db.Clipboard.id==id).first()
        if not item:
            return {'code': -1, 'msg': '[%s]不存在' % id}
        session.delete(item)
        session.commit()
        return {'code': 0, 'msg': '删除[%s]成功' % id}
    except BaseException as e:
        return {'code': -1, 'msg': str(e)}

@get('/clipboard', 'clipboard.html')
async def clipboard(*, request):
    session = db.create_session()
    result = [clipboard for clipboard in session.query(db.Clipboard)]
    result.reverse()
    for item in result:
        item.content = item.content.replace('<', '&lt;').replace('>', '&gt;')
    return {'clipboards': result}

@get('/clipboard/items')
async def clipboard_items(request):
    data = {}
    try:
        session = db.create_session()
        items = [{'content': item.content} for item in session.query(
            db.Clipboard).order_by(db.Clipboard.id.desc())]
        data['items'] = items
    except BaseException as e:
        data['items'] = []
    return {'code': 0, 'msg': data}

@post('/clipboard')
async def save_clipboard(*, text, request):
    try:
        if not text or not text.strip():
            return {'code': -1, 'field': 'text', 'msg': 'text is null'}
        session = db.create_session()
        user = request.__user__
        if user:
            clipboard = db.Clipboard(content=text, user_id=user.id, user_name=user.name, user_image=user.image)
        else:
            clipboard = db.Clipboard(content=text, user_name='guest')
        session.add(clipboard)
        session.commit()
        data = {'code': 0, 'msg': clipboard.id}
        return data
    except BaseException as e:
        return {'code': -1, 'msg': str(e)}
